package io.renren.modules.test.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpClientUtil {
    public static String doPostTestFourWithHeader(String url, String paramJson,Map<String,String> header) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost httpPost = new HttpPost(url);

        for(Map.Entry<String,String> map:header.entrySet()){
            httpPost.addHeader(map.getKey(), map.getValue());
        }

        StringEntity entity=new StringEntity(paramJson,"utf-8");
        httpPost.setEntity(entity);

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

//    public static void main(String[] args) {
//        Map<String,String> map=new HashMap<String, String>();
//        map.put("kbn-version","6.7.0");
//        map.put("Content-Type","application/json");
//        String paramJson="{\n" +
//                "  \"size\": 100,\n" +
//                "  \"from\": 0,\n" +
//                "  \"query\": {\n" +
//                "    \"bool\": {\n" +
//                "      \"must\": [\n" +
//                "        {\n" +
//                "          \"range\": {\n" +
//                "            \"@timestamp\": {\n" +
//                "              \"gte\": \"2019-08-26 13:00:00\",\n" +
//                "              \"lte\": \"2019-08-30 14:00:00\",\n" +
//                "               \"format\": \"yyyy-MM-dd HH:mm:ss\"\n" +
//                "            }\n" +
//                "          }\n" +
//                "        }\n" +
//                "      ]\n" +
//                "    }\n" +
//                "  }\n" +
//                "}";
//        HttpClientUtil.doPostTestFourWithHeader("http://kibana.biz.com/api/console/proxy?path=_search&method=POST",paramJson,map);
//    }
}
